import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
import Query

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.out.write('<html><body>')
    user = users.get_current_user()
    if user:
      self.response.out.write("<h2>Hello, <i>"+ user.nickname()+"</i></h2><h3>10 Latest WaveAlpha queries</h3>")
    else:
      self.redirect(users.create_login_url(self.request.uri))
      
    results = db.GqlQuery("SELECT * FROM Query ORDER BY date DESC LIMIT 10")
    for result in results:
      if result.images:
        self.response.out.write("<img src=\""+result.images[0]+"\"<br/>"+str(result.date)+"<hr />")
      else:
        self.response.out.write("No result for query, \""+result.search_string+"\"<br/>"+str(result.date)+"<hr />")
      
    self.response.out.write('</body></html>')

application = webapp.WSGIApplication(
                                     [('/', MainPage)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
